﻿using ArtMath.Component;
using ArtMath.Control;
using ArtMath.Flag;
using ArtMath.CommonType;
using ArtMath.Resource;
using ArtMath.Setting;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace ArtMath.Window
{
    public partial class ComponentsManagerWindow : DockContent
    {
        [Browsable(false)]
        public LayerControl LinkedLayer { get; private set; }
        public void SketchPad_Layer_Activated(LayerControl sender)
        {
            splitContainer1.Panel1.Controls.Clear();
            LinkedLayer = sender;
            if (LinkedLayer == null)
            {
                //toolStrip1.Enabled = false;
                Enabled = false;
                Text = Resources.JoinLocalizedString("Component", "Manager");
            }
            else
            {
                splitContainer1.Panel1.Controls.Add(LinkedLayer);
                LinkedLayer.BringToFront();
                LinkedLayer.RefreshStatus();
                //toolStrip1.Enabled = true;
                Enabled = true;
            }
        }
        public ComponentsManagerWindow()
        {
            InitializeComponent();
            splitContainer1.Panel2Collapsed = true;
            ChangeColorTheme(Settings.Instance.ColorTheme);
        }
        public void ChangeColorTheme(UIColorTheme theme)
        {
            switch (theme)
            {
                case UIColorTheme.Light:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015LightTheme1);
                    break;
                case UIColorTheme.Blue:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015BlueTheme1);
                    break;
                case UIColorTheme.Dark:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015DarkTheme1);
                    break;
            }
        }
        void EnableVSRenderer(VisualStudioToolStripExtender.VsVersion version, ThemeBase theme)
        {
            visualStudioToolStripExtender1.SetStyle(toolStrip1, version, theme);
            visualStudioToolStripExtender1.SetStyle(cmsSet, version, theme);
        }
        public bool SearchChecked
        {
            get { return tsbSearch.Checked; }
            set { tsbSearch.Checked = value; }
        }
        private void tsbDel_Click(object sender, EventArgs e)
        {
            DeleteComponents();
        }
        public IList<Base> DeleteComponents(bool all = false, bool enableKey = true)
        {
            bool selectedFlag = LinkedLayer.SelectedItems.Count > 0, sft = enableKey && Flags.Shift;
            if (sft)
            {
                if (MessageBox.Show(string.Format(Resources.Translate("DeleteObjectAsk"), Resources.Translate("Component")), Resources.Translate("Ask"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return null;
                }
            }
            IList<Base> res = LinkedLayer.Delete(all, !sft);
            if (selectedFlag && LinkedLayer.SelectedItems.Count == 0)
            {
                LinkedLayer.AutoSelect();
            }
            return res;
        }
        private void tsbSearch_CheckStateChanged(object sender, EventArgs e)
        {
            if (tsbSearch.Checked)
            {
                plSearch.Visible = true;
                searchCheck();
            }
            else
            {
                plSearch.Visible = false;
                foreach (LayerItem item in LinkedLayer.Items)
                {
                    if (item.ObjectState == ObjectState.Normal)
                    {
                        item.ItemContainer.BackColor = Color.White;
                        item.Searched = false;
                    }
                }
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            searchCheck();
        }
        void searchCheck()
        {
            if (tbSearchText.TextLength > 0)
            {
                string subitemText, textboxText = tbSearchText.Text;
                foreach (LayerItem item in LinkedLayer.Items)
                {
                    if (item.ObjectState == ObjectState.Normal)
                    {
                        subitemText = item.Name;
                        if (!区分大小写ToolStripMenuItem.Checked)
                        {
                            subitemText = subitemText.ToLower();
                            textboxText = textboxText.ToLower();
                        }
                        if (subitemText.Contains(textboxText))
                        {
                            if (全字匹配ToolStripMenuItem.Checked)
                            {
                                item.Searched = subitemText.Length == textboxText.Length;
                                if (item.Searched)
                                {
                                    item.ItemContainer.BackColor = Color.Orange;
                                }
                                else
                                {
                                    item.ItemContainer.BackColor = Color.White;
                                }
                            }
                            else
                            {
                                item.ItemContainer.BackColor = Color.Orange;
                                item.Searched = true;
                            }
                        }
                    }
                    else
                    {
                        item.ItemContainer.BackColor = Color.White;
                        item.Searched = false;
                    }
                }
            }
            else
            {
                foreach (LayerItem item in LinkedLayer.Items)
                {
                    if (item.ObjectState == ObjectState.Normal)
                    {
                        item.ItemContainer.BackColor = Color.White;
                        item.Searched = false;
                    }
                }
            }
        }

        private void btSet_Click(object sender, EventArgs e)
        {
            cmsSet.Show(btnSearchSettings, new Point(0, btnSearchSettings.Height));
        }
        private void tsbFolder_Click(object sender, EventArgs e)
        {
            FolderLayerItem item = new FolderLayerItem(Resources.Translate("NewFolder"));
            LinkedLayer.Add(item);
            item.Panel_DblClick(sender, e);
        }

        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {
            if (splitContainer1.Panel1.Controls.Count == 2)
            {
                e.Graphics.DrawLines(new Pen(Color.FromArgb(130, 135, 144), 1), new Point[] {
                    new Point(0, toolStrip1.Height), new Point(0, splitContainer1.Panel1.Height - 1),
                    new Point(splitContainer1.Panel1.ClientSize.Width - 1, splitContainer1.Panel1.ClientSize.Height - 1),
                    new Point(splitContainer1.Panel1.ClientSize.Width - 1, toolStrip1.Height), new Point(0, toolStrip1.Height) });
            }
        }
        private void tsbClearTrack_Click(object sender, EventArgs e)
        {
            ClearTracks();
        }
        public void ClearTracks()
        {
            foreach (LayerItem item in LinkedLayer.SelectedItems)
            {
                if (item.LinkedObj != null)
                {
                    ShapeBase sb = item.LinkedObj as ShapeBase;
                    if (sb != null)
                    {
                        sb.ClearTracks();
                        LinkedLayer.Pad.Document.Modified = true;
                    }
                }
            }
        }
        private void tsbUp_Click(object sender, EventArgs e)
        {
            for (int i = LinkedLayer.SelectedItems.Count - 1; i >= 0; i--)
            {
                LinkedLayer.SelectedItems[i].Swap(LinkedLayer.SelectedItems[i].Index + 1);
            }
            LinkedLayer.Pad.Document.Modified = true;
        }

        private void tsbDown_Click(object sender, EventArgs e)
        {
            foreach (LayerItem item in LinkedLayer.SelectedItems)
            {
                item.Swap(item.Index - 1);
            }
            LinkedLayer.Pad.Document.Modified = true;
        }

        private void tsbLock_ButtonClick(object sender, EventArgs e)
        {
            SetLock(true);
        }
        public void SetLock(bool value)
        {
            foreach (LayerItem item in LinkedLayer.SelectedItems)
            {
                if (item.LinkedObj != null)
                {
                    ShapeBase sb = item.LinkedObj as ShapeBase;
                    if (sb != null)
                    {
                        sb.Locked = value;
                    }
                }
            }
            LinkedLayer.Pad.Document.Modified = true;
        }
        private void 解锁UToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetLock(false);
        }

        private void tsbCopy_Click(object sender, EventArgs e)
        {
            CopyObject();
        }
        public void CopyObject()
        {
            CopyObject(LinkedLayer.Pad, LinkedLayer.SelectedItems.Select((LayerItem item) => { return item.LinkedObj; }));
        }
        private void 区分大小写ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            searchCheck();
        }

        private void 全字匹配ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            searchCheck();
        }

        private void tsbPaste_Click(object sender, EventArgs e)
        {
            PasteObject(LinkedLayer.Pad);
        }
        public void PasteObject(SketchPad sender)
        {
            foreach (object item in Program.Clipboard)
            {
                if (item == null) continue;
                ICopyPaste icp = item as ICopyPaste;
                if (icp == null) continue;
                icp.CopyAndPaste(sender);
            }
        }

        private void tsbFormatPainter_CheckedChanged(object sender, EventArgs e)
        {
            if (tsbFormatPainter.Checked)
            {
                CopyStyle(LinkedLayer.Pad, LinkedLayer.SelectedItems[0].LinkedObj);
            }
            else
            {
                PasteStyle(LinkedLayer.Pad, LinkedLayer.SelectedItems.Select((LayerItem item) => { return item.LinkedObj; }));
            }
        }
        public void PasteStyle(SketchPad sender, IEnumerable<Base> objs)
        {
            if (Program.FormatSource == null) return;
            sender.OldCoordinate = Program.FormatSource.Pad.Coordinate;
            foreach (Base item in objs)
            {
                if (item == null) continue;
                item.UseFormat(Program.FormatSource);
            }
            sender.OldCoordinate = null;
            sender.Document.Modified = true;
        }
        private void tsbCut_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("剪切ToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbCut.Enabled);
        }

        private void tsbCopy_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("复制CToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbCopy.Enabled);
        }

        private void tsbPaste_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("粘贴PToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbPaste.Enabled);
        }

        private void tsbDel_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("删除DToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbDel.Enabled);
        }

        private void tsbClearTrack_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("清除轨迹ToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbClearTrack.Enabled);
        }

        private void tsbLock_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("锁定LToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbLock.Enabled);
            Program.WinMain.NotifyMenuPropertyChanged("解锁UToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbLock.Enabled);
        }

        private void tsbCut_Click(object sender, EventArgs e)
        {
            CutObject();
        }
        public void CutObject()
        {
            IList<Base> dels = DeleteComponents(false, false);
            if (dels?.Count > 0)
            {
                CopyObject(LinkedLayer.Pad, dels);
            }
        }
        public void CopyObject(SketchPad sender, IEnumerable<object> objs)
        {
            Program.Clipboard = objs.ToArray();
            tsbPaste.Enabled = Flags.PasteObjectEnabled = true;
        }
        public void CopyStyle(SketchPad sender, Base obj)
        {
            Program.FormatSource = obj;
            Flags.PasteStyleEnabled = true;
        }

        private void ComponentsManagerWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                DockState = DockState.Hidden;
                e.Cancel = true;
            }
            Program.WinMain.ComponentManagerMenu.Checked = false;
        }
        public void SketchPad_Layer_RefreshWindowsStatus(LayerControl sender, LayerControl.RefreshWindowsStatusEventArgs e)
        {
            tsbUp.Enabled = e.MoveUpEnabled;
            tsbDown.Enabled = e.MoveDownEnabled;
            tsbFormatPainter.Enabled = e.FormatPainterEnabled && (tsbFormatPainter.Checked || sender.SelectedItems.Count == 1);
            tsbCut.Enabled = tsbCopy.Enabled = tsbDel.Enabled =
            tsbLock.Enabled = tsbClearTrack.Enabled = sender.SelectedItems.Count > 0;
            if (sender.SelectedItems.Count == 0)
            {
                Text = Resources.JoinLocalizedString("Component", "Manager");
            }
            else
            {
                Text = $"{Resources.JoinLocalizedString("Component", "Manager")} - " + (sender.SelectedItems.Count == 1 ? sender.SelectedItems[0].Name : $"({Resources.JoinLocalizedString("Multiple", "Component")})");
            }
        }

        private void tsbSearch_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("查找FToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbSearch.Enabled);
        }
    }
}
